package com.easyattendance.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.easyattendance.nls.UseProperties;
import com.easyattendance.model.AllTimeSlots;
import com.easyattendance.model.Section;
import com.easyattendance.model.Class;
import com.easyattendance.model.Teacher;
import com.easyattendance.model.TimeSlot;
import com.easyattendance.services.AddAllTimeSlotsService;
import com.easyattendance.services.AddSectionService;
import com.easyattendance.services.AddTeacherService;
import com.easyattendance.services.AddTimeSlotsSettingsService;
import com.easyattendance.services.TimeTableService;
import com.easyattendance.util.AllTimeSlotsArrayClass;

@WebServlet("/AddTimeSlotsServlet")
public class AddTimeSlotsServlet extends HttpServlet {

	protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// lastLecTimeDt = format.parse(end_time.toString());
		
		boolean null_fields=false;
		boolean dispatcherFlag=false;
		Date recess1Time = null, recess2Time = null, startTime = null, endTime = null;
		try {
		 
		 if(request.getParameter("start_time")!=null && request.getParameter("end_time")!=null && request.getParameter("recess1_time")!=null && request.getParameter("recess2_time")!=null)
		 {
			startTime = format.parse("2010-10-10 "+request.getParameter("start_time")+":00");
			endTime = format.parse("2010-10-10 "+request.getParameter("end_time")+":00");
			recess1Time = format.parse("2010-10-10 "+request.getParameter("recess1_time")+":00");
			recess2Time = format.parse("2010-10-10 "+request.getParameter("recess2_time")+":00");

			System.out.println("start and end times: " + startTime + " "+ endTime);
		 }
		 else
			 null_fields=true;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		int lectureMinutes=0,recess1Minutes=0,recess2Minutes=0;
		
		if(!request.getParameter("lecture_duration").equals("") && !request.getParameter("recess1_duration").equals("") && !request.getParameter("recess2_duration").equals(""))
		{
			lectureMinutes = Integer.parseInt(request.getParameter("lecture_duration"));
			recess1Minutes = Integer.parseInt(request.getParameter("recess1_duration"));
			recess2Minutes = Integer.parseInt(request.getParameter("recess2_duration"));
		}
		else
		{
			 null_fields=true;
		}

		String sectionEmail = (String) request.getSession().getAttribute("currentUser");
		AddSectionService addSectionService = new AddSectionService();

		Section section = addSectionService.getSectionBySectionEmail(sectionEmail);

		AddTimeSlotsSettingsService timeSlotsSettings = new AddTimeSlotsSettingsService();
		AddAllTimeSlotsService timeSlotsService = new AddAllTimeSlotsService();

		TimeSlot timeSlot = new TimeSlot();
		timeSlot.setSection(section);

		boolean res = timeSlotsSettings.ifAlreadyExists(timeSlot);

		String ID = null;
		boolean result = false;

	  if(!null_fields)
	  {
		if (!res) {

			Properties labels = UseProperties.loadProperties("Attendance.properties");

			//labels = UseProperties.incrementTimeSlotIdCounterValue(labels);
			ID = UseProperties.getTimeSlotIdPrefix(labels)	+ timeSlotsSettings.getTimeslotIdValue();
			
			timeSlot = new TimeSlot(ID,section, startTime, endTime, lectureMinutes, recess1Time, recess1Minutes, recess2Time, recess2Minutes);
			result = timeSlotsSettings.addTimeSlotSettings(timeSlot);
			
			System.out.println(".................Time Slot table created................... ");
			
    		TimeTableService service = new TimeTableService();
    		
    		//set the days in util(GLOBAL) class
    		String[] daysMap = service.getDaysHeader();
    		AllTimeSlotsArrayClass.setDays(daysMap);
    		boolean result1 = false;
    		
    		//set the timeslots calculated in util(GLOBAL) class
    		String[] timeSlotsMap = service.getTimeSlotsMap(section.getSection_id());
    		//AllTimeSlotsArrayClass.setAllTimeSlots(timeSlotsMap);'
    		AllTimeSlots allTimeSlots = new AllTimeSlots();
    		
    		for(int i=0; i<timeSlotsMap.length; i++) {
    			//allTimeSlots = new AllTimeSlots(timeSlotsMap[i], section);
    			allTimeSlots.setSection_id(section.getSection_id());
    			allTimeSlots.setTime_slot(timeSlotsMap[i]);
    			allTimeSlots.setSection(section);
    			result1 = timeSlotsService.addAllTimeSlots(allTimeSlots);
    			System.out.println("result2: "+result1);
    		}
    		
    		if(result1) {
    			result1 = timeSlotsService.createExcelTemplate(section.getSection_id(), sectionEmail);
    		}
    		

		} else {
			 request.setAttribute("timeslotAlreadyExists","Section already has a timeslot defined.");
			 dispatcherFlag=true;
		}
	  

		try {

			if (result) {
				 request.setAttribute("timeslotAdded","Timeslot genearated successfully.");
				 dispatcherFlag=true;
				
			} else {
				 request.setAttribute("timeslotNotAdded","Timeslot could not be genearated successfully.");
				 dispatcherFlag=true;
			}
			
		} finally {
			//out.close();
		}
	  }
	  
	  if(null_fields)
	  {
		  request.setAttribute("null_values", "All * fields are compulsory.");
		  RequestDispatcher rd = request.getRequestDispatcher("views/section/generateTimeslot.jsp");
      	  rd.forward(request, response);
	  }
	  else if(dispatcherFlag)
	  {
		  RequestDispatcher rd = request.getRequestDispatcher("views/section/generateTimeslot.jsp");
      	  rd.forward(request, response);
	  }
	  
	}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	@Override
	public String getServletInfo() {
		return "Short description";
	}// </editor-fold>
}
